from app import db
from datetime import datetime
from typing import Dict, Any

class BaseModel(db.Model):
    """模型基类"""
    __abstract__ = True

    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            column.name: getattr(self, column.name)
            for column in self.__table__.columns
        }

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'BaseModel':
        """从字典创建实例"""
        return cls(**{
            key: value for key, value in data.items()
            if key in cls.__table__.columns
        })

    def update_from_dict(self, data: Dict[str, Any]) -> None:
        """从字典更新实例"""
        for key, value in data.items():
            if hasattr(self, key):
                setattr(self, key, value) 